package com.loan.system.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loan.common.constant.UserConstants;
import com.loan.common.core.domain.PageQuery;
import com.loan.common.core.domain.entity.SysUser;
import com.loan.common.core.domain.model.LoginUser;
import com.loan.common.core.page.TableDataInfo;
import com.loan.common.enums.DelFlagEnum;
import com.loan.common.exception.ServiceException;
import com.loan.common.helper.LoginHelper;
import com.loan.common.utils.StringUtils;
import com.loan.system.domain.AddressEntity;
import com.loan.system.domain.CompanyEntity;
import com.loan.system.domain.SysConfig;
import com.loan.system.domain.req.CompanyReq;
import com.loan.system.mapper.CompanyMapper;
import com.loan.system.service.CompanyService;
import com.loan.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author shiguang on 2022/9/5 10:50
 */
@RequiredArgsConstructor
@Service
public class CompanyServiceImpl implements CompanyService {

    private final CompanyMapper companyMapper;

    private final ISysUserService userService;

    @Override
    public TableDataInfo<CompanyEntity> selectPageCompanyList(CompanyEntity companyEntity, PageQuery pageQuery) {
        Map<String, Object> params = companyEntity.getParams();
        LambdaQueryWrapper<CompanyEntity> lqw = new LambdaQueryWrapper<CompanyEntity>()
                .like(StringUtils.isNotBlank(companyEntity.getName()), CompanyEntity::getName, companyEntity.getName())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        CompanyEntity::getCreateTime, params.get("beginTime"), params.get("endTime"));
        Page<CompanyEntity> page = companyMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    /**
     * 校验名称是否重复
     * @param company
     * @return
     */
    @Override
    public String checkNameUnique(CompanyEntity company) {
        Long id = ObjectUtil.isNull(company.getId()) ? -1L : company.getId();
        CompanyEntity companyEntity = companyMapper.selectOne(new QueryWrapper<CompanyEntity>()
                .eq("name", company.getName())
                .eq("del_flag", DelFlagEnum.NORMAL.value()));
        if (ObjectUtil.isNotNull(companyEntity) && companyEntity.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 添加公司
     * @param company
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCompany(CompanyReq company) {
        CompanyEntity entity = new CompanyEntity();
        entity.setStatus("0");
        entity.setName(company.getName());
        int i = companyMapper.insert(entity);
        //保存后台账号
        SysUser user = new SysUser();
        user.setPassword(BCrypt.hashpw(company.getPassword()));
        user.setUserName(company.getUsername());
        user.setPhonenumber(company.getPhone());
        user.setCompanyId(entity.getId());
        userService.insertUser(user);
        return i ;
    }

    @Override
    public CompanyEntity selectCompanyById(Long id) {
        return companyMapper.selectById(id);
    }

    @Override
    public int addCompany(CompanyEntity entity) {
        if ("1".equals(checkNameUnique(entity))){
           throw new ServiceException("名称已存在");
        }
        return companyMapper.insert(entity);
    }

    @Override
    public int updateCompany(CompanyEntity entity) {
        return companyMapper.updateById(entity);
    }

    @Override
    public int deleteCompanyById(Long id) {
        return companyMapper.deleteById(id);
    }

    @Override
    public int updateStatus(CompanyEntity entity) {
        return companyMapper.updateById(entity);
    }

    @Override
    public List<CompanyEntity> selectList() {
        return companyMapper.selectList(new QueryWrapper<CompanyEntity>().eq("del_flag","0").orderByDesc("create_time"));
    }

    /**
     * 根据登录人信息获取公司详情
     * @return
     */
    @Override
    public CompanyEntity getDetail() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser.getCompanyId()!=null){
            return companyMapper.selectById(loginUser.getCompanyId());
        }
        return null;
    }

}
